package yxy.game.pm2.command.arena;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.bean.module.rank.RankWorship;
import yxy.game.pm2.bean.module.rank.RankWorshipPlayer;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ArenaMessage;
import yxy.game.pm2.module.arena.ArenaHandle;
import yxy.game.pm2.module.arena.RankArena;

import java.util.Collection;

/** 竞技场 竞技场排行榜 */
@MessageType(proto = Command.ArenaRank, classtype = ArenaMessage.ArenaRankRequest.class)
public class CMD_ArenaRank extends Command<ArenaMessage.ArenaRankRequest> {

	@Override
	public void execute(MessageSource messageSource, ArenaMessage.ArenaRankRequest request) {
		String playerCode = messageSource.getTag();

		ArenaMessage.ArenaRankResponse.Builder response = ArenaMessage.ArenaRankResponse.newBuilder();

		RankArena rankArena = RankArena.getRank(playerCode);
		try {
			Collection<RankEntry> top = rankArena.top(rankArena.topSize());
			int rank = 0;
			ArenaHandle handle = new ArenaHandle();

			RankWorship worship = rankArena.getWorship();
			RankWorshipPlayer worshipPlayer = RankWorshipPlayer.get(playerCode, worship);
			for (RankEntry entry : top) {
				String pCode = entry.getKey();
				int score = entry.getValue().intValue();

				ArenaMessage.RankArena.Builder builder = ArenaMessage.RankArena.newBuilder();

				builder.setRank(++rank);
				builder.setPlayerInfo(handle.oppoInfo(pCode));
				builder.setScore(score);
				builder.setFans(worship.getScore(pCode));
				builder.setLiked(worshipPlayer.getWorshiped().contains(pCode));
				response.addRank(builder);
			}
			{
				int playerRank = 0;
				int score = 0;
				RankEntry entry = rankArena.get(playerCode);
				if (entry != null) {
					playerRank = rankArena.rank(playerCode);
					score = entry.getValue().intValue();
				}

				ArenaMessage.RankArena.Builder builder = ArenaMessage.RankArena.newBuilder();
				builder.setRank(playerRank);
				builder.setPlayerInfo(handle.oppoInfo(playerCode));
				builder.setScore(score);
				response.setMy(builder);
			}

			response.setTimes(worshipPlayer.remainTimes());

			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}

	}

	private void send(MessageSource messageSource, ArenaMessage.ArenaRankResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}